<?php

declare(strict_types=1);

namespace app\controller\admin\esxsys;

use think\Request;
use think\facade\Validate;
use app\eslib\EsUtils;
use app\model\esxsys\ConfigsModel;

/**
 * 系统配置 控制器
 * @version 1.0.0
 */
class Configs
{
    // 控制器中间件
    protected $middleware = [\app\middleware\JwtAuthForAdmin::class];

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index(Request $request)
    {
        $groupName = $request->param('group_name', '');
        $searchText = $request->param('search_text', '');
        $pageSize = intval($request->param('page_size', 10));

        $data = ConfigsModel::where(function ($query) use ($searchText, $groupName) {
            if ($searchText) {
                $query->where(function ($query) use ($searchText) {
                    $query->where('id', intval($searchText))->whereOr('user_name', 'like', "%{$searchText}%");
                });
            }
            if ($groupName) {
                $query->where('group_name', $groupName);
            }
        })->order('status')->order('sort, id')->append(['component_name_text', 'status_text', 'is_locked_text'])->paginate($pageSize);

        foreach ($data as $row) {
            if ($row['component_name'] == 'radio') {
                // 把 0=关闭&1=开启 转换为 [['value'=>0,'text'=>'关闭'],['value'=>1,'text'=>'开启']]
                $dataTemp = [];
                $pairArr = explode('&', $row['component_data']);
                foreach ($pairArr as $pairStr) {
                    $itemArr = explode('=', $pairStr);
                    $dataTemp[] = ['value' => $itemArr[0], 'text' => $itemArr[1]];
                }
                $row['component_data'] = $dataTemp;
            }
        }
        return json(EsUtils::stdMessage(true, '', $data));
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $formData = $request->param();
        $validator =  Validate::rule([
            'group_name|分组名称' => 'require|max:60',
            'conf_name|变量名' => 'require|max:60',
            'conf_title|变量标题' => 'require|max:100',
            'conf_tip|变量提示' => 'require|max:100',
            'conf_value|变量值' => 'require|max:1000',
            'component_name|组件名称' => 'require|max:30',
            'component_data|组件数据' => 'require|max:200',
            'default_value|组件默认值' => 'require|max:30',
            'validate_rule|验证规则' => 'require|max:100',
            'sort|排序权重' => 'require|number',
            'status|状态' => 'require|number',
            'is_locked|是否锁定' => 'require|number',
        ]);
        if (!$validator->check($formData)) {
            return json(EsUtils::stdMessage(false, $validator->getError()));
        }
        // 表单数据处理
        // ...
        try {
            $model = ConfigsModel::create($formData);
            return json(EsUtils::stdMessage(true, '', $model->id));
        } catch (\Exception $ex) {
            return json(EsUtils::stdMessage(false, $ex->getMessage()));
        }
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        if (!is_numeric($id)) {
            return json(EsUtils::stdMessage(false, 'id值无效', $id));
        }
        if ($id > 0) {
            $model = ConfigsModel::find($id);
            if (!$model) {
                return json(EsUtils::stdMessage(false, '记录不存在'));
            }
        } else {
            $model = new ConfigsModel();
            $model->component_name = '';
            $model->status = 1;
            $model->is_locked = 0;
            $model->sort = 999;
            $model->status = 1;
            $model->is_locked = 0;
        }
        $data = [
            'data' => $model,
            'component_name_data' => $model->getComponentNameDataAttr(),
            'status_data' => $model->getStatusDataAttr(),
            'is_locked_data' => $model->getIsLockedDataAttr(),
        ];
        return json(EsUtils::stdMessage(true, $id, $data));
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        // 特殊模式的更新操作
        $model = $request->param('_mode', '');
        switch ($model) {
            case 'copy':
                // 复制指定的资源
                try {
                    $affected = ConfigsModel::copy($id);
                    return json(EsUtils::stdMessage(true, '', $affected));
                } catch (\Exception $ex) {
                    return json(EsUtils::stdMessage(false, $ex->getMessage()));
                }
            case 'uoc':
                // uoc = update one column，更新某一字段
                $field = $request->param('k', '');
                $value = $request->param('v', '');
                try {
                    $affected = ConfigsModel::where('id', $id)->update([$field => $value]);
                    return json(EsUtils::stdMessage(true, '', $affected));
                } catch (\Exception $ex) {
                    return json(EsUtils::stdMessage(false, $ex->getMessage()));
                }
                break;
            default:
                break;
        }

        // 常规更新操作
        $formData = $request->param();
        if (isset($formData['_mode'])) {
            unset($formData['_mode']);
        }
        $validator =  \think\facade\Validate::rule([
            'group_name|分组名称' => 'require|max:60',
            'conf_name|变量名' => 'require|max:60',
            'conf_title|变量标题' => 'require|max:100',
            'conf_tip|变量提示' => 'require|max:100',
            'conf_value|变量值' => 'require|max:1000',
            'component_name|组件名称' => 'require|max:30',
            'component_data|组件数据' => 'require|max:200',
            'default_value|组件默认值' => 'require|max:30',
            'validate_rule|验证规则' => 'require|max:100',
            'sort|排序权重' => 'require|number',
            'status|状态' => 'require|number',
            'is_locked|是否锁定' => 'require|number',
        ]);
        if (!$validator->check($formData)) {
            return json(EsUtils::stdMessage(false, $validator->getError()));
        }
        try {
            $affected = ConfigsModel::where('id', $id)->update($formData);
            return json(EsUtils::stdMessage(true, '', $affected));
        } catch (\Exception $ex) {
            return json(EsUtils::stdMessage(false, $ex->getMessage()));
        }
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        try {
            $affected = ConfigsModel::destroy($id);
            return json(EsUtils::stdMessage(true, '', $affected));
        } catch (\Exception $ex) {
            return json(EsUtils::stdMessage(false, $ex->getMessage()));
        }
    }
}
